1. Two Sum
https://leetcode.com/problems/two-sum/description/
Definition
Intuition
The idea is to iterate and for each index we should look for another index that contains a complement so:
To find the complement we shall use a lookup table. We don't need to preprocess the list to build the lookup table, we can fill it while iterating the list.
For the current element , look for an entry with value in the lookup table which gives us an index or empty. If the entry exists, return the response , otherwise add the entry to the lookup table and repeat the process.
Ilustration
Example array: [1, 2, 0, 4, 6]
Target sum: 5
1st iteration
At the first iteration, starts at index 0 and the lookup table is empty. The current element is , so we should look for the complement but the lookup table is empty, so we just add the current element to the lookup table and increment .
| Row | Key | Value |
|---|---|---|
2nd iteration
The current element is , so we should look for the complement but there is no entry with key in the table, so we just add the current element to the lookup table and increment .
| Row | Key | Value |
|---|---|---|
| 1 | 1 | 0 |
3rd iteration
The current element is , so we should look for the complement but there is no entry with key in the table, so we just add the current element to the lookup table and increment .
| Row | Key | Value |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 1 |
4th iteration
The current element is , so we should look for the complement ant it exists in the table at row which gives us the index , so the answer is
| Row | Key | Value |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 1 |
| 3 | 0 | 2 |
Implementation
Click to reveal implementation
class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
visited_numbers: dict[int, int] = {}
for i, n in enumerate(nums):
complement_index = visited_numbers.get(target - n, None)
if complement_index is not None:
return [complement_index, i]
visited_numbers[n] = i
Tests
import pytest
from .solution import Solution
@pytest.mark.parametrize('numbers,target,expected', [
([0, 1], 1, [0, 1]),
([1, 2, 3], 5, [1, 2]),
])
def test_solution(numbers, target, expected):
result = Solution().twoSum(numbers, target)
assert result == expected
Time complexity
In the worst case, the complement will be found at the last index so we need to iterate all the input and fill/query table elements. The iteration is and the insertions/queries takes time assuming no collisions. So, the final time complexity is .
Space complexity
In the worst case we need to fill the table with entries, so the space complexity is .